package org.ssssssss.magicapi;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.ssssssss.magicapi.core.config.MagicAPIProperties;
import org.ssssssss.magicapi.core.config.MagicPluginConfiguration;
import org.ssssssss.magicapi.core.model.Plugin;
import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.ssssssss.magicapi.mqtt.MqttServerStarter;
import org.ssssssss.magicapi.ws.R2rWsServerStarter;

import com.sduept.i1.I1Server;

@Configuration
public class MagicNetworkConfiguration implements MagicPluginConfiguration {

	private final MagicAPIProperties properties;

	@Autowired
	private MagicAPIService service;
	

	@Value("${magic-api.mqtt.init-start:false}")
	public boolean mqttInitStart;
	@Value("${magic-api.mqtt.port:1883}")
	public int mqttPort;
	@Value("${magic-api.mqtt.messageApi:}")
	public String mqttMessageApi;
	
	@Value("${magic-api.ws.init-start:false}")
	public boolean wsInitStart;
	@Value("${magic-api.ws.port:9326}")
	public int wsPort;
	@Value("${magic-api.ws.byteApi:}")
	public String wsByteApi;
	@Value("${magic-api.ws.textApi:}")
	public String wsTextApi;
	@Value("${magic-api.ws.closeApi:}")
	public String wsCloseApi;
	
	@Value("${magic-api.i1.init-start:false}")
	public boolean i1InitStart;
	@Value("${magic-api.i1.port:5002}")
	public int i1Port;
	
	public MagicNetworkConfiguration(MagicAPIProperties properties) {
		this.properties = properties;
	}


	@Override
	public Plugin plugin() {
		System.out.println("网络服务插件:wsInitStart="+wsInitStart+";mqttInitStart="+mqttInitStart);
		if(service!=null) {
			Const.setService(service);
			Const.setMqttApi(mqttMessageApi);
			Const.setWsApi(wsByteApi, wsTextApi, wsCloseApi);
			try {
				if(wsInitStart)
					R2rWsServerStarter.start(wsPort);
				if(mqttInitStart)
					MqttServerStarter.start(mqttPort);
				if(i1InitStart)
					I1Server.start("", i1Port);
				//CdzlbServer.start("", 5001);
				//
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else {
			System.out.println("网络服务:@Autowired MagicAPIService ERROR");
		}
		return new Plugin("网络服务:mqtt+websocket+socket");
	}
}
